package com.yutian.selfservice.support;

import com.github.pagehelper.Page;
import com.yutian.selfservice.support.mapper.AllServiceMapper;
import com.yutian.selfservice.support.utils.PageSupport;
import com.yutian.selfservice.support.utils.Result;
import com.yutian.selfservice.support.utils.SpringUtil;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
public class AllService extends ListService {

//    @Override
//    public String getName() {
//        return null;
//    }

    /**
     * 多个节点分页查询  先分页id  再在字表中进行查询
     *
     * @return
     */
    @Override
    public Result query() {
        PageSupport.startPage(this);
        Page<AllService> page = (Page<AllService>) SpringUtil.getBean(AllServiceMapper.class).selectList(this);
        if (CollectionUtils.isEmpty(page)) {
            return Result.successPage(new ArrayList(), page.getTotal());
        }
        return searchByCondition(page);
    }
    private Result searchByCondition(Page<AllService> page) {
        List<ListService> list = new ArrayList<>();
        Map<Long, List<Long>> map = page.stream().collect(
                Collectors.groupingBy(AllService::getType, Collectors.mapping(x -> x.getId(), Collectors.toList())));
        map.forEach((x, y) -> {
            if (x <= 3) {
                list.addAll(new ServiceGuide().selectByIds(y));
            } else if (x == 4) {
                list.addAll(new QuestionService().selectByIds(y));
            } else {
                list.addAll(new UrlService().selectByIds(y));
            }
        });
        List<ListService> sortList = new ArrayList<>();

        //按照查询条件的排序 组装数据
        Map<String,List<ListService>> itemGroup = list.stream().collect(Collectors.groupingBy(x->x.getType()+"_"+x.getId()));
        page.forEach(x->sortList.add(itemGroup.get(x.getType()+"_"+x.getId()).get(0)));
        return Result.successPage(sortList, page.getTotal());
    }

    @Override
    public List<? extends ListService> selectByIds(List<Long> ids) {
        return null;
    }

    @Override
    public Result details() {
        return Result.success();
    }


}
